<template>
  <el-dialog :title="!dataForm.id ? '新增签到时间配置' : '编辑签到时间配置'" :visible.sync="visible" width="600px" :close-on-click-modal="false" append-to-body>
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="师训项目" prop="trainId">
            <el-select v-model="dataForm.trainId" placeholder="请选择师训项目" filterable clearable :style="{ width: '100%' }" @change="onTrainChange">
              <el-option v-for="item in trainOptions" :key="item.id" :label="item.title" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="配置日期" prop="configDate">
            <el-date-picker v-model="dataForm.configDate" type="date" placeholder="请选择配置日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="datePickerOptions" :style="{ width: '100%' }" />
            <div v-if="selectedTrainDateRange" class="date-range-hint">
              <small style="color: #909399;">可选日期范围: {{ selectedTrainDateRange }}</small>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="时段名称" prop="periodName">
            <el-select v-model="dataForm.periodName" placeholder="请选择时段" :style="{ width: '100%' }">
              <el-option label="上午" value="AM" />
              <el-option label="下午" value="PM" />
              <el-option label="晚上" value="EVE" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker v-model="dataForm.startTime" placeholder="请选择开始时间" format="HH:mm" value-format="HH:mm" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker v-model="dataForm.endTime" placeholder="请选择结束时间" format="HH:mm" value-format="HH:mm" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迟到阈值" prop="lateMinutes">
            <el-input-number v-model="dataForm.lateMinutes" placeholder="迟到阈值(分钟)" :min="0" :max="60" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序码" prop="sortCode">
            <el-input-number v-model="dataForm.sortCode" placeholder="排序码" :min="0" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="启用状态" prop="isEnabled">
            <el-switch v-model="dataForm.isEnabled" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入备注" :rows="3" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getTrainSignTimeConfigInfo, createTrainSignTimeConfig, updateTrainSignTimeConfig } from '@/api/campus/trainSignTimeConfig'
import { getTrainSelector } from '@/api/campus/train'

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        trainId: '',
        configDate: '',
        periodName: '',
        startTime: '',
        endTime: '',
        lateMinutes: 15,
        sortCode: 0,
        isEnabled: true,
        remark: ''
      },
      dataRule: {
        trainId: [{ required: true, message: '请选择师训项目', trigger: 'change' }],
        configDate: [{ required: true, message: '请选择配置日期', trigger: 'change' }],
        periodName: [{ required: true, message: '请选择时段名称', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }, { validator: this.validateEndTime, trigger: 'change' }],
        lateMinutes: [{ required: true, message: '请输入迟到阈值', trigger: 'blur' }]
      },
      trainOptions: []
    }
  },
  computed: {
    // 显示选中师训的日期范围
    selectedTrainDateRange() {
      const selectedTrain = this.trainOptions.find(train => train.id === this.dataForm.trainId)
      if (!selectedTrain || !selectedTrain.startDate || !selectedTrain.endDate) {
        return ''
      }

      try {
        const startDate = new Date(selectedTrain.startDate)
        const endDate = new Date(selectedTrain.endDate)

        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          return '日期格式无效'
        }

        const formatDate = date => {
          return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0')
        }

        return `${formatDate(startDate)} 至 ${formatDate(endDate)}`
      } catch (error) {
        return '日期解析错误'
      }
    },
    // 日期选择器选项，限制只能选择师训日期范围内的日期
    datePickerOptions() {
      const selectedTrain = this.trainOptions.find(train => train.id === this.dataForm.trainId)

      if (!selectedTrain || !selectedTrain.startDate || !selectedTrain.endDate) {
        // 如果没有选中师训或师训缺少日期信息，则不限制日期选择
        return {}
      }

      return {
        disabledDate(time) {
          try {
            // 处理日期格式，确保能正确解析
            const startDate = new Date(selectedTrain.startDate)
            const endDate = new Date(selectedTrain.endDate)

            // 检查日期是否有效
            if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
              console.warn('师训日期格式无效:', {
                startDate: selectedTrain.startDate,
                endDate: selectedTrain.endDate
              })
              return false // 如果日期无效，不限制选择
            }

            // 设置时间为当天的开始和结束，避免时间部分的影响
            const timeStart = new Date(time.getFullYear(), time.getMonth(), time.getDate())
            const rangeStart = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())
            const rangeEnd = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate())

            return timeStart.getTime() < rangeStart.getTime() || timeStart.getTime() > rangeEnd.getTime()
          } catch (error) {
            console.error('日期比较出错:', error)
            return false // 出错时不限制选择
          }
        }
      }
    }
  },
  methods: {
    init(id, defaultTrainId) {
      this.dataForm.id = id || ''
      this.visible = true
      this.getTrainOptions()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else if (defaultTrainId) {
          // 新增时设置默认师训项目
          this.dataForm.trainId = defaultTrainId
        }
      })
    },
    async getTrainOptions() {
      try {
        const res = await getTrainSelector()
        if (res.code === 200) {
          this.trainOptions = res.data || []
        }
      } catch (error) {
        console.error('获取师训列表失败:', error)
      }
    },
    // 师训项目改变时清空配置日期
    onTrainChange() {
      this.dataForm.configDate = ''
    },
    async getInfo() {
      try {
        const res = await getTrainSignTimeConfigInfo(this.dataForm.id)
        if (res.code === 200) {
          this.dataForm = { ...this.dataForm, ...res.data }
        }
      } catch (error) {
        console.error('获取配置信息失败:', error)
      }
    },
    validateEndTime(rule, value, callback) {
      if (!value || !this.dataForm.startTime) {
        callback()
        return
      }
      const startTime = new Date(`2000-01-01 ${this.dataForm.startTime}`)
      const endTime = new Date(`2000-01-01 ${value}`)
      if (endTime <= startTime) {
        callback(new Error('结束时间必须大于开始时间'))
      } else {
        callback()
      }
    },

    dataFormSubmit() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          try {
            const res = this.dataForm.id ? await updateTrainSignTimeConfig(this.dataForm) : await createTrainSignTimeConfig(this.dataForm)

            if (res.code === 200) {
              this.$message.success(this.dataForm.id ? '更新成功' : '创建成功')
              this.visible = false
              this.$emit('refreshDataList')
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error('操作失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped></style>
